package com.xwh.shop.user.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xwh.shop.common.exceptions.BusinessException;
import com.xwh.shop.common.exceptions.enums.Resp;
import com.xwh.shop.user.model.dto.AdminLoginDTO;
import com.xwh.shop.user.model.entity.Admin;
import com.xwh.shop.user.model.entity.Role;
import com.xwh.shop.user.model.vo.AdminLoginVO;
import com.xwh.shop.user.service.mapper.AdminMapper;
import com.xwh.shop.user.service.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import com.xwh.shop.user.service.service.RoleService;
import com.xwh.shop.user.service.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwh
 * @since 2025-07-15
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {


    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RoleService roleService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private HttpServletRequest request;


    @Override
    public AdminLoginVO login(AdminLoginDTO adminLoginDTO) {

        if(adminLoginDTO == null
                || !StringUtils.hasText(adminLoginDTO.getUsername())
                || !StringUtils.hasText(adminLoginDTO.getPassword())){
            log.warn("登录参数不完整: {}", adminLoginDTO);
            throw new BusinessException(Resp.INVALID_PARAM);
        }

        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(adminLoginDTO.getUsername()),Admin::getMobile,adminLoginDTO.getUsername());
        Admin admin = this.getOne(wrapper);

        if(admin == null){
            log.warn("管理员账号不存在: {}", adminLoginDTO.getUsername());
            throw new BusinessException(Resp.INVALID_USERNAME);
        }

        log.info("password:{}",passwordEncoder.encode(adminLoginDTO.getPassword()));

        if(!passwordEncoder.matches(adminLoginDTO.getPassword(),admin.getPassword())){
            log.warn("管理员密码错误, 账号: {}", adminLoginDTO.getUsername());
            throw new BusinessException(Resp.INVALID_PASSWORD);
        }

        // claims是一个接口不能new一个 需要用Jwts.claims()来拿到一个

        Role role = this.roleService.getRoleByAdminId(admin.getId());
        if(role == null){
            throw new BusinessException(Resp.UNAUTHORIZED);
        }


        Claims claims = Jwts.claims();
        // 由于直接用adminId来判断 用户的权限需要从 admin表->admin_role_ref->role->role_permission->permission太麻烦。
        // 所以直接把roleId写入token，这样就可以直接从role->role_permission->permission
        claims.put("adminId",admin.getId());
        claims.put("roleId",role.getId());
        claims.put("roleName",role.getRoleName());

        log.info("管理员登录成功: {}, 角色: {}", admin.getId(), role.getRoleName());

        return new AdminLoginVO(
                jwtUtil.generateAccessToken(claims),
                jwtUtil.generateRefreshToken(claims)
        );
    }

    @Override
    public boolean checkToken() {
        // 从请求头中获取token，解析出用户ID，然后查询用户信息
        String token = request.getHeader("Authorization");
        String res = jwtUtil.validateAccessToken(token);
        return "Valid".equals(res);
    }
}
